package com.wenlin.userservice.zookeeper;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.RetryUntilElapsed;

/***
 *  Created with IntelliJ IDEA.
 *  Author:  wenlin
 *  Date:  2018/3/27 16:56
 *  Description:
 **/
public class Lock2 {

    /** zookeeper地址 */
    static final String CONNECT_ADDR = "127.0.0.1:2181";
    /** session超时时间 */
    static final int SESSION_OUTTIME = 1000000;

    static int count = 10;
    public static void genarNo(){
        try {
            count--;
            System.out.println(count);
        } finally {

        }
    }

    public static void main(String[] args) throws Exception {

        //1 重试策略：初试时间为1s 重试10次
        //RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
        RetryPolicy retryPolicy = new RetryUntilElapsed(10000,100);
        //2 通过工厂创建连接
        CuratorFramework cf = CuratorFrameworkFactory.builder()
                .connectString(CONNECT_ADDR)
                .sessionTimeoutMs(SESSION_OUTTIME)
                .retryPolicy(retryPolicy)
//                    .namespace("super")
                .build();
        //3 开启连接
        cf.start();

        //4 分布式锁
        final InterProcessMutex lock = new InterProcessMutex(cf, "/test10");
        final CountDownLatch countdown = new CountDownLatch(1);

        for(int i = 0; i < 10; i++){
            new Thread(() -> {
                try {
                   // countdown.await();
                    //加锁
                    System.out.println("我是第" + Thread.currentThread().getId() + "号线程，我准备获取锁");
                    if(lock.acquire(50, TimeUnit.SECONDS)) {
                        System.out.println(lock.getParticipantNodes()+"=============");

                        //-------------业务处理开始
                        System.out.println("我是第" + Thread.currentThread().getId() + "号线程，我获取锁成功");
                        System.out.println(Thread.currentThread().getId() + ":获取锁,执行业务");
                        SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = new Date();
                        System.out.println(Thread.currentThread().getId() + "业务执行时间:"+time.format(date));
                        //Thread.sleep(1000);
                        Thread.sleep(4000);
                    }else{
                        System.out.println("我是第" + Thread.currentThread().getId() + "号线程，我获取锁超时");
                        System.out.println(Thread.currentThread().getId() + ":锁已被其他线程占用，等待");
                    }
                    //-------------业务处理结束
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        //释放
                        lock.release();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            },"t" + i).start();
        }
        //Thread.sleep(100);

        // countdown.countDown();
    }
}
